package westeel.dataserver.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class DataSourceUtils {
    final static Logger logger = LoggerFactory.getLogger(DataSourceUtils.class);
    public static final String SPRING_DATASOURCE_PREX = "spring.datasource.";
    public static final String SPRING_DATASOURCE_REGULAR_EXP = "spring.datasource.([\\D|\\d]+).driverClassName";
    private static final Pattern springDataSourceNamePattern = Pattern.compile(SPRING_DATASOURCE_REGULAR_EXP);
    static public Map<String, Object> getPropertiesStartAt(Properties properties,String prex) {
        Map<String,Object> propMap = new LinkedHashMap<>();
        String keyPrex = prex+".";
        String key;
        for (Map.Entry<Object, Object> pairs : properties.entrySet()) {
            key = pairs.getKey().toString();
            if(!key.startsWith(keyPrex)) continue;
            key = key.substring(keyPrex.length());
            key = CamelNameUtils.CamelName4Variable(key);
            propMap.put(key,pairs.getValue());
        }
        return propMap;
    }
    public static Set<String> getDataSourceNames(Properties properties) {
        Set<String> names = new LinkedHashSet<>();
        for (Enumeration<Object> iter = properties.keys();iter.hasMoreElements();) {
            String key = (String)iter.nextElement();
            Matcher matcher = springDataSourceNamePattern.matcher(key);
            if(matcher.find()){
                String name = matcher.group(1);
                names.add(name);
            }
        }
        return names;
    }
    public static void addDataSourceInfo(Properties properties,String dataSourceName,Map<String, Object> props) {
        for(Map.Entry<String, Object> prop: props.entrySet()){
            properties.put(SPRING_DATASOURCE_PREX+dataSourceName +"."+prop.getKey(),prop.getValue());
        }
    }
    public static void keepDataSourceInfo(Properties properties) {
        Set<Object> keys = properties.keySet();
        Set<Object> toDel = new HashSet<>();
        for(Object key: keys){
            if(!((String)key).startsWith(SPRING_DATASOURCE_PREX)){
                toDel.add(key);
            }
        }
        for(Object key: toDel) {
            properties.remove(key);
        }
    }

    public static void removeDataSourceInfo(Properties properties, String beanName4DataSource) {
        Set<Object> toDel = new HashSet<>();
        for(Object key: properties.keySet()){
            if(((String)key).startsWith(SPRING_DATASOURCE_PREX+beanName4DataSource)){
                toDel.add(key);
            }
        }
        for(Object key: toDel) {
            properties.remove(key);
        }
    }
}
